package com.atguigu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Date:2022/11/9
 * Author:ybc
 * Description:
 */
@Configuration //将当前类标识为配置类
@EnableWebSecurity //开启SpringSecurity的默认功能
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启注解配置权限
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //配置BCryptPasswordEncoder验证密码是否正确的bean,解密程序
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth
        //.inMemoryAuthentication()
        //.withUser("admin")
        //        //.password("{noop}123456")
        //.password("$2a$10$HsYavh.wvpre4xRnDjcW/uZ99nUgI2aNv1f5CJZdXiMaCW.srohBm")
        //        .roles("admin")
        //        .authorities("admin.create");
        //.password("$2a$10$HsYavh.wvpre4xRnDjcW/uZ99nUgI2aNv1f5CJZdXiMaCW.srohBm")

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //访问父类的configure(http)方法，使用SpringSecurity所提供的默认的功能
        //super.configure(http);
        //设置资源的访问规则
        http.authorizeRequests() //对资源的请求进行授权
                .antMatchers("/static/**", "/login") //通过ant风格的路径匹配请求
                .permitAll() //匿名访问（即不需要登录就可以访问）
                .anyRequest() //其他所有请求
                .authenticated(); //需要认证才能访问
        //设置自定义的登录页面
        http.formLogin()
                .loginPage("/login") //设置自定义的登录页面
                .usernameParameter("username") //登录页面表单中表示用户名的请求参数名
                .passwordParameter("password") //登录页面表单中表示密码的请求参数名
                .loginProcessingUrl("/login_process") //处理登录请求的请求路径
                .defaultSuccessUrl("/") //登录成功默认访问的请求的请求路径,可添加默认值为true，默认登录成功返回的页面始终为/
                .failureUrl("/login"); //登录失败默认访问的请求的请求路径
        //自定义注销功能
        http.logout()
                .logoutUrl("/logout") //退出登录的请求的请求路径
                .logoutSuccessUrl("/login"); //退出登录成功要访问的请求的请求路径
        //自定义访问被拒绝的处理程序
        http.exceptionHandling().accessDeniedHandler(new SHFAccessDeniedHandler());
        //禁用csrf功能,防跨域伪造
        http.csrf().disable();
        //允许访问iframe中的内容
        http.headers().frameOptions().disable();
    }
}
